package net.udp;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.Scanner;

/**
 * 	用于输出的写的
 * @author Administrator
 *
 */
public class Client extends Thread{
	
	// 端口号
	private int port;
	
	// 地址
	private InetAddress address;

	public Client(int port, InetAddress address) {
		super();
		this.port = port;
		this.address = address;
	}
	
	/**
	 * 	不断写数据
	 */
	@Override
	public void run() {
		DatagramSocket socket = null;
		Scanner scanner = null;
		try {
			// 创建socket
			socket = new DatagramSocket();
			
			scanner = new Scanner(System.in);
			while(true) {
				String in = scanner.nextLine();
				// 退出
				if("bye".equals(in)) {
					break;
				}
				
				// 发送消息
				byte[] content = in.getBytes();
				DatagramPacket packet = new DatagramPacket(content, 0, content.length, address, port);
				socket.send(packet);
			}
		} catch (SocketException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if(socket != null) {
				socket.close();
			}
			if(scanner != null) {
				scanner.close();
			}
		}
	}

}
